package com.start.handler;

import java.io.File;
import java.net.URL;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

@Controller
@RequestMapping("/file")
public class FileUpLoad {


	@RequestMapping("/test")
	public void test(HttpServletRequest req) {
		System.out.println("FileUpLoad.test()");

		// 使用fileupLoad组件完成文件上传
		// 上传的位置
		String realPath = req.getSession().getServletContext().getRealPath("/uploads/");
		System.out.println(realPath);
		// 判断该文件夹是否存在
		File file = new File(realPath);
		if (!file.exists()) {
			// 不存在则创建文件夹
			file.mkdir();
		}

		// 获取应用路径
		URL resource = this.getClass().getResource("/");
		System.out.println("---" + resource);
		URL resource2 = this.getClass().getResource("");
		System.out.println(resource2);
		URL resource3 = Thread.currentThread().getContextClassLoader().getResource("");
		System.out.println(resource3);
		String requestURI = req.getRequestURI();
		System.out.println(requestURI);
		String path = this.getClass().getClassLoader().getResource("/").getPath();
		System.out.println(path);
	}

	/**
	 * 传统方式上传文件
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/fileupload")
	public String testFileUpLoading(HttpServletRequest request) throws Exception {
		System.out.println("FileUpLoad.testFileUpLoading()");

		// 使用fileupLoad组件完成文件上传
		// 上传的位置
		// String realPath =
		// request.getSession().getServletContext().getRealPath("/uploads/");
		// System.out.println(realPath);
		String realPath = "E:\\project\\springMVC\\WebContent\\uploads";

		// 判断该文件夹是否存在
		File file = new File(realPath);
		if (!file.exists()) {
			// 不存在则创建文件夹
			file.mkdirs();
		}
		// 解析request对象，获取上传文件项
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(factory);
		// 解析request
		List<FileItem> parseRequest = fileUpload.parseRequest(request);
		// 遍历文件项
		for (FileItem fileItem : parseRequest) {
			// 进行判断，当前fileItem对象是否是上传文件项
			if (fileItem.isFormField()) {// 说明是普通表单项
				System.out.println("普通表单项");
			} else {// 说明是上传文件项
				// 获取上传表单文件域名称
				String fieldName = fileItem.getFieldName();
				// 获取上传文件名称
				String name = fileItem.getName();
				System.out.println(fieldName);
				System.out.println(name);
				String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
				String uuidFileName = uuid + "_" + name;
				// 完成文件上传
				fileItem.write(new File(realPath, uuidFileName));
				// 删除临时文件
				fileItem.delete();
			}
		}
		return "successResponse";
	}

	/**
	 * SpringMVC方式上传文件按
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/testFileUpLoadingSpringMVC")
	public String testFileUpLoadingSpringMVC(MultipartFile file2, String text2) throws Exception {
		String realPath = "E:\\project\\springMVC\\WebContent\\uploads";
		// 判断该文件夹是否存在
		File file = new File(realPath);
		if (!file.exists()) {
			// 不存在则创建文件夹
			file.mkdirs();
		}
		// 获取上传表单文件域名称
		String originalFilename = file2.getOriginalFilename();
		System.out.println(originalFilename);
		String name = file2.getName();
		System.out.println(name);
		String contentType = file2.getContentType();
		System.out.println(contentType);
		System.out.println(text2 + "--->");
		String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
		String uuidFileName = uuid + "_" + originalFilename;
		file2.transferTo(new File(realPath, uuidFileName));
		return "successResponse";
	}

	/**
	 * 跨服务器上传文件
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/testOther")
	public String testOther(MultipartFile file2) throws Exception {
		// 要有两个服务器才能进行测试。
		String url = "http://localhost:8089/springMVCFileServer/upload/";
		// 获取上传表单文件域名称
		String originalFilename = file2.getOriginalFilename();
		String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
		String uuidFileName = url + uuid + "_" + originalFilename;

		// 创建客户端对象
		Client client = new Client();
		// 和文件服务器进行连接
		WebResource resource = client.resource(uuidFileName);
		// 上传文件
		resource.put(file2.getBytes());
		return "successResponse";
	}
}
